import 'package:flutter/material.dart';
import "package:eventsource/eventsource.dart";
import 'dart:convert';
import 'package:http/http.dart' as http;

void main() async {
  runApp(SampleApp());
}

class SampleApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Sample App',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {

  List<Map<String, dynamic>> listOfColumns = [];
  bool _pause = false;
  EventSource eventSource;
  String fileContent;
  final String mainTableURL = "http://10.213.20.43:9910/msi/mainTableInfo";
  final String fileURL = "http://10.213.20.43:9910/msi/getFile/";

  void _onChanged(bool value) => setState(() => _pause = value);

  @override
  void initState() {
    super.initState();
    _loadData();
  }

  _loadData() async {
    eventSource = await EventSource.connect(mainTableURL);

    // listen for events
    eventSource.listen((Event event) {
      setState(() {
        String data = "${event.data}";
        print(data);
        print(json.decode(data));
        print("Pause: $_pause");
        if (!_pause) {
          listOfColumns.add(json.decode(data));
          print(listOfColumns.length);
        }
      });
    });
  }

  _loadFile(String uuid) async {
    http.get(fileURL + uuid)
      .then((response) {
        print("Response body: ${response.body}");
        showDialog<void>(
          context: context,
          barrierDismissible: false, // user must tap button!
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text('文件内容'),
              content: SingleChildScrollView(
                child: ListBody(
                  children: <Widget>[
                    Text(response.body)
                  ],
                ),
              ),
              actions: <Widget>[
                FlatButton(
                  child: Text('OK'),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
              ],
            );
          },
        );
    });
  }

  var latestItemTextStyle = TextStyle(
//      fontSize: 32.0,
      color: Colors.red[900],
      fontWeight:FontWeight.w600
  );

  DataRow _getDataRow(index) {
    if (index == listOfColumns.length - 1) { // The latest item with special style.
      return DataRow(
        cells: <DataCell>[
          DataCell(
            new GestureDetector(
              onTap: () {
                _loadFile(listOfColumns[index]["id"]);
              },
              child: Text(listOfColumns[index]["fileName"], style: latestItemTextStyle,),
            ),
          ),
          DataCell(Text(listOfColumns[index]["startTime"], style: latestItemTextStyle,)),
          DataCell(Text(listOfColumns[index]["endTime"], style: latestItemTextStyle,)),
          DataCell(Text(listOfColumns[index]["status"], style: latestItemTextStyle,)),
        ],
      );
    } else {
      return DataRow(
        cells: <DataCell>[
          DataCell(
            new GestureDetector(
              onTap: () {
                _loadFile(listOfColumns[index]["id"]);
              },
              child: new Text(listOfColumns[index]["fileName"]),
            ),
          ),
          DataCell(Text(listOfColumns[index]["startTime"])),
          DataCell(Text(listOfColumns[index]["endTime"])),
          DataCell(Text(listOfColumns[index]["status"])),
        ],
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('文件列表'),
        actions: <Widget>[
          new Center(
            child: new Text('ON',
                style: new TextStyle(
                    fontWeight: FontWeight.bold,
                    color: Colors.greenAccent)
            ),
          ),
          new Switch(
            value: _pause,
            onChanged: _onChanged,
            activeTrackColor: Colors.blueGrey,
            activeColor: Colors.grey,
          ),
          new Center(
            child: new Text('OFF',
                style: new TextStyle(
                    fontWeight: FontWeight.bold,
                    color: Colors.grey)
            ),
          ),
          new Center(
            child: new Padding(padding: EdgeInsets.all(10.0)),
          ),
        ],
      ),
      body: Container(
        padding: EdgeInsets.all(16.0),
        child: new ListView(
          children: <Widget>[
            new DataTable(
              columns: [
                DataColumn(label: Text('File')),
                DataColumn(label: Text('Start')),
                DataColumn(label: Text('End')),
                DataColumn(label: Text('Status')),
              ],
              rows: List.generate(listOfColumns.length,
                      (index) => _getDataRow(listOfColumns.length - 1 - index)
              ),
            )
          ],
        ),
      ),
    );
  }
}
